package org.pausd.gunn.compsci;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.io.InputStreamReader;
/**
 * The server-side proxy for a local player class, but treat it as any player. It will forward
 * messages which will be received and parsed by NetworkGame, which will call the appropriate
 * methods on the Player class.
 * @author CodyS
 *
 */
public class NetworkPlayer extends Player implements Messager {
	private Socket connect;
	private BufferedReader reader;
	private PrintWriter writer;
	public NetworkPlayer(Game g,Socket s) {
		super(g);
		connect = s;
		try {
			reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
			writer = new PrintWriter(s.getOutputStream());
			Thread t = new Thread(new NetworkListener(this,reader));
			t.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * Receive a message and call the appropriate methods on the LocalGame class.
	 * @param message The message to send
	 */
	@Override
	public void receive(String message) {
		String[] info = message.split(" ");
		if(info[0].equals("add")) {
			getGame().addToCounter(Integer.parseInt(info[1]));
		}
		else if(info[0].equals("ready")) {
			getGame().playerReady(this);
		}
	}
	/**
	 * Send a message to the NetworkGame class to be parsed
	 * @param message The message to send.
	 */
	@Override
	public void send(String message) {
		writer.println(message);
		writer.flush();
	}

	@Override
	public void leave() {
		getGame().removePlayer(this);
		try {
			reader.close();
			writer.close();
			connect.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	/**
	 * Notifies the player what the current value of the counter is.
	 * @param num The value of the counter
	 */
	public void counter(int num) {
		send("counter "+num);
	}

	@Override
	/**
	 * Tells the player that it is his turn and that he should add to the counter.
	 */
	public void doTurn() {
		send("turn");
	}

	@Override
	/**
	 * Tells the player to decide if he is ready or not.
	 */
	public void ready() {
		send("ready");
	}

	@Override
	/**
	 * Tell the player that the game has started.
	 */
	public void started() {
		send("start");
	}
}
